package Login;

import Dao.communityDao;
import Dao.communityDaoImpl;
import been.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.SQLException;

@WebServlet(value = "/register")
public class registerServlet extends HttpServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        communityDao dao = new communityDaoImpl();
        User user = null;
        String message =null;

        int user_id=0;
        String user_idParam=request.getParameter("user_id");
        if(user_idParam==null){
            message="id不能为空";
            request.setAttribute("message",message);
            request.getRequestDispatcher("/WEB-INF/Login/register.jsp").forward(request,response);
            return;
        }
        else{
            try{
                user_id=Integer.parseInt(user_idParam);
            }
            catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }

        String user_name=request.getParameter("user_name");
        if(user_name==null||user_name.isEmpty()){
            message="账号不能为空";
            request.setAttribute("message",message);
            request.getRequestDispatcher("/WEB-INF/Login/register.jsp").forward(request,response);
            return;
        }

        String password=request.getParameter("password");
        if(password==null||password.isEmpty()){
            message="密码不能为空";
            request.setAttribute("message",message);
            request.getRequestDispatcher("/WEB-INF/Login/register.jsp").forward(request,response);
            return;
        }

        String role=request.getParameter("role");
        if(role==null||role.isEmpty()){
            message="角色不能为空";
            request.setAttribute("message",message);
            request.getRequestDispatcher("/WEB-INF/Login/register.jsp").forward(request,response);
            return;
        }

        try{
            user=new User(user_id,user_name,password,role);
            int res= dao.addUser(user);
            if(res>0){
                message="注册成功";
                request.setAttribute("message",message);
                request.getRequestDispatcher("/WEB-INF/Login/register.jsp").forward(request,response);
            }
            else
            {
                message="注册失败";
                request.setAttribute("message",message);
                request.getRequestDispatcher("/WEB-INF/Login/register.jsp").forward(request,response);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }
}
